/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.nacos;


import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.AppInfo;
import com.alibaba.csp.sentinel.dashboard.rule.AbstractDynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.convert.Converter;
import com.alibaba.csp.sentinel.dashboard.rule.util.ConfigIdUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: shaozeming
 * @date: 2022/8/8 15:24
 * @description:
 **/
public class FlowRuleNacosProvider extends AbstractDynamicRuleProvider {

    private final ConfigService configService;
    private final NacosConfig nacosConfig;

    public FlowRuleNacosProvider(ConfigService configService,NacosConfig nacosConfig){
        this.configService =configService;
        this.nacosConfig =nacosConfig;
    }

    @Override
    protected List<RuleEntity> getPrivateRules(AppInfo appInfo, Class<?> clz) throws Exception {
        String rules = configService.getConfig(appInfo.getApp() + ConfigIdUtil.getKey(clz),
                nacosConfig.getGroupId(), nacosConfig.getTimeout());
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return Converter.decode(appInfo,rules,clz);
    }

    @Override
    protected List<RuleEntity> getDefaultRules(AppInfo appInfo, Class<?> clz) throws Exception {
        String defaultKey = ConfigIdUtil.getDefaultKey(clz);
        if(defaultKey ==null ||defaultKey.length() ==0){
            return new ArrayList<>();
        }
        String rules = configService.getConfig(appInfo.getApp() + defaultKey,
                nacosConfig.getGroupId(),  nacosConfig.getTimeout());
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return Converter.decode(appInfo,rules,clz);
    }


}
